var validator;
var cd = new Date();
var minYear = cd.getFullYear() - 120;
var minMon = cd.getMonth();
var minDay = cd.getDate();
var maxYear = cd.getFullYear()-1;
var maxMon = minMon;
var maxDay = minDay;
var bdayErrMsg = 'Your age should between 1~120 years old.';

$(document).ready(function(){
	// initialize selected display text
	$('select').each(
		function(){
				var val = $(this).siblings().val();
				$(this).find('option').removeAttr('selected');
				$(this).find('option[value='+val+']').attr('selected','selected')
			}
	);
	$('select').change( function (e) {
		var newVal = e.target.value;
		$(this).siblings().val(newVal);
		$(this).children('option').removeAttr('selected');
		$(this).children('option[value='+newVal+']').attr('selected','selected');
	});
	
	$.validator.addMethod("date", function(date, element) {
                return this.optional(element) || date.match(/^\d{4}-((0\d)|(1[012]))-(([012]\d)|3[01])$/);
            }, "Please specify a valid date : YYYY-MM-DD");
	
	$.validator.addMethod('mindate',function(v,el,minDate){
				if (this.optional(el)){
					return true;
				}
				var curDate = new Date($(el).val());
				return curDate >= minDate;
			}, bdayErrMsg);
	$.validator.addMethod('maxdate',function(v,el,maxDate){
				if (this.optional(el)){
					return true;
				}
				var curDate = new Date($(el).val());
				return curDate <= maxDate;
			}, bdayErrMsg);
			
	validator = $('#profileForm').validate({
		rules: {
		  name: {
			required: true,
		  },
		  gender: {
			required: true,
		  },
		  pid: {
			required: true,
		  },
		  bday: {
			mindate: new Date(minYear,minMon,minDay),
			maxdate: new Date(maxYear,maxMon,maxDay),
			required: true,
			date: true,
		  },
		  phoneNum: {
			required: true,
		  },
		  nationality: {
			required: true,
		  },
		  emgcyContact:{
			required: true,
		  },
		  emgcyContPhone:{
			required: true,
		  },
		},

		highlight: function(element) {
			var attr = $(element).attr("style")
			if( typeof attr != 'undefined' && attr != false ) {
				$(element).css({'border-color':'#b94a48', 'border-width':'2px'});	
			}
			else {
				$(element).closest('.form-group').addClass('has-error');
			}
		},
		unhighlight: function(element, errorClass, validClass) {
			var attr = $(element).attr("style")
			if( typeof attr != 'undefined' && attr != false ) {
				$(element).css({'border-color':'', 'border-width':'1px'});
			}
			else {
				$(element).closest('.form-group').removeClass('has-error');
			}
		},
		
		submitHandler: function(form) {
			form.submit();
		},
	
	});

	$('.enter-enable').keypress(function (e){
		if( e.keyCode == 13 ) {
			$('#profile_modify').click();
		}
	});
	
	$('#profile_modify').click(function(e){
		if( $("#profileForm").valid() == false ){
			validator.focusInvalid();
			return;
		}
		
		$('#profile_form_errormsg').hide();
		
		// auth state : waiting
		ajax_waiting();
		
		data = $('#profileForm').serialize();
		Dajaxice.users.profilejson(resultCallback, {'form':data}, {'error_callback': ajax_error});
		
		e.preventDefault();
	});
});

function resultCallback(data) {
		console.log("dajax callback " + data.result);
		 
		// auth state : finish
		ajax_finish();
		
		$('#profile_form_errormsg .msg').text(data.msg);
		
		if( data.result == "success_modify" )
		{
			$('#profile_form_errormsg ').show();
			$('#profile_form_errormsg .alert').removeClass('alert-danger');
			$('#profile_form_errormsg .alert').addClass('alert-success');
		}
		else// if( data.result == "failed_modify" )
		{
			$('#profile_form_errormsg ').show();
			$('#profile_form_errormsg .alert').removeClass('alert-success');
			$('#profile_form_errormsg .alert').addClass('alert-danger');
			
			switch(data.result)
			{
				case "illegal_fields_bday":
					var $validator = $("#profileForm").validate();
					errors = { bday: bdayErrMsg };
					$validator.showErrors(errors);
					break;
			}
		}
		
		/*
		// 1. success signup
		if( data.result == "success_signup" )
		{
			$('#signup_success_alert').show();
			$('#new_user_alert_info').hide();
			setTimeout(
						function(){
								$('#signup_success_alert').hide();
								window.location = data.redirect_to;
							},
						1500);
			return;
		}
		// 2. success login
		else if( data.result == "success_login" )
		{
			window.location = data.redirect_to;
			return;
		}
		*/
		/*
		// refresh captcha if any error occurs
		$('#recaptcha_reload_btn')[0].click();
		
		// 0.5. captcha failed
		if( data.result == "captcha_fail")
		{
			$('#auth_form_errormsg_captcha').show();
			$('#recaptcha_response_field').css({'border-color':'#b94a48', 'border-width':'2px'});
			$('#recaptcha_response_field').focus();
			
			$('#authdlg').on('hidden', function () {
				$('#auth_form_errormsg_captcha').hide();
				$('#recaptcha_response_field').css({'border-color':'', 'border-width':'1px'});
			});			
		}
		// 1. auth faild  (add error icon and error msg)
		else if( data.result == "invalid_authencate")
		{
			$('#auth_form_errormsg').show();
			$('#authdlg').on('hidden', function () {
				$('#auth_form_errormsg').hide();
			});
		}
		*/
}

function ajax_error() {
	ajax_finish();
}

function ajax_init() {
	$('#profile_form_errormsg').hide();
	
	// show control
	$('#profile_modify').removeAttr("disabled");
	// hide loading gif
	$('#ajax_wait_img').hide();
}

function ajax_waiting() {
	
	// hide control
	$('#profile_modify').attr("disabled","disabled");
	// show loading gif
	$('#ajax_wait_img').show();
}

function ajax_finish() {
	ajax_init();
}